package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-hub/inits"
	"post-hub/internal/dto"
	"post-hub/internal/model"
	"post-hub/pkg"
	"post-hub/response"
	"time"
)

func Login(c *gin.Context) {

	var user model.User
	err := c.ShouldBind(&user)
	if err != nil {
		response.Error(c, "解析失败")
		return
	}
	var dbUser model.User
	err = dto.FindTel(&dbUser, user.Tel)
	if err != nil {
		return
	}
	if dbUser.ID == 0 {
		newUser := model.User{
			Image:    user.Image,
			Username: user.Username,
			Tel:      user.Tel,
		}
		err = dto.Create(&newUser)
		if err != nil {
			response.Error(c, "注册失败")
			return
		}
		response.Success(c, "注册成功", newUser.ID)
		return
	}

	handler, err := pkg.TokenHandler(int64(dbUser.ID))
	if err != nil {
		return
	} else {
		response.Success(c, "登录成功", handler)

		marshal, err := json.Marshal(&dbUser)
		if err != nil {
			response.Error(c, "解析失败")
			return
		}
		inits.Rdb.Set(inits.Ctx, "user", marshal, time.Minute*3)
		inits.DB.Begin()
		login := model.Login{
			Time:   time.Now(),
			Status: "success",
		}
		dto.CreateLogin(&login)
		inits.DB.Commit()
	}

}
